<!-- 食品列表 -->
<template>
  <div class="myadmin-foodlist">
    <top-header></top-header>
    <div class="foodSearch">
        <el-input placeholder="请输入食品名称" v-model="foodSearch" class="input-with-select" style="width:500px;margin:10px 0px"></el-input>
          <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>   
    </div>
    <div class="myadmin-foodlist-table">
      <el-table :data="foodListData" border stripe>
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-form
              label-position="left"
              
              label-width="80px"
              inline
              size="normal"
            >
              <el-form-item label="评分">
                <span>{{ props.row.rating }}</span>
              </el-form-item>
              <el-form-item label="销量">
                <span>{{ props.row.tips }}</span>
              </el-form-item>
              <!-- restaurant_id -->
              <el-form-item label="餐馆id">
                <span>{{ props.row.restaurant_id }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column label="食品名称" prop="name"> </el-table-column>
        <el-table-column label="食品图片" prop="image_path">
          <template slot-scope="scope">
            <el-image
              :src="baseImgPath + '/' + scope.row.image_path"
              style="width: 200px; height: 200px"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column label="食品描述" prop="description"> </el-table-column>
        <el-table-column label="评分" prop="rating"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" size="default" @click="handleEdit(scope)"
              >编辑</el-button
            >
            <el-button
              type="primary"
              size="default"
              @click="handleDelete(scope)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog title="修改食品信息" :visible.sync="dialogVisible" width="50%">
      <el-form
        :rules="rules"
        :model="form"
        ref="form"
        label-width="80px"
        :inline="false"
      >
        <el-form-item label="食品名称" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="食品介绍" prop="description">
          <el-input v-model="form.description" ></el-input>
        </el-form-item >
        <el-form-item label="食品分类">
             <el-select v-model="value" placeholder="请选择" >
        <el-option
            v-for="item in foodtype"
            :key="item.value"
            :label="item.label"
            :value="item.value">
        </el-option>
     </el-select>
        </el-form-item>
       
        <el-form-item label="食品图片">
          <el-upload 
            class="avatar-uploader"
            :action="BASE_URL + 'v1/addimg/avatar'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="selectTable.image_path" :src="baseImgPath + selectTable.image_path" class="avatar" style="border:1px dashed #ddd"/>
            <i v-else class="el-icon-plusavatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item>
            <el-table :data="specs">
                <el-table-column label="规格" prop="specs_name"></el-table-column>
                <el-table-column label="包装费" prop="packing_fee"></el-table-column>
                <el-table-column label="价格" prop="price"></el-table-column>
                <el-table-column label="操作">
                <template slot-scope="scope">
                     <el-button type="danger" @click="subspecs(scope)">删除</el-button>
                </template>
                 </el-table-column>
                  </el-table>
            <el-button type="primary" style="margin-left:300px;margin-top:10px" @click="addSpecs=true">添加规格</el-button>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" size="default" @click="handleSubmit('form')">确定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="添加规格" :visible.sync="addSpecs">
        <el-form :rules="specsRules" :model="specsForm" label-width="100px" >
            <el-form-item label="规格" prop="specs_name">
                <el-input v-model="specsForm.specs_name"></el-input>
            </el-form-item>
            <el-form-item label="包装费">
                <el-input-number v-model="specsForm.packing_fee"  :min="0" :max="10" label="包装费"></el-input-number>
            </el-form-item>
             <el-form-item label="价格">
                <el-input-number v-model="specsForm.price"  :min="0" :max="1000" label="价格"></el-input-number>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" size="default" @click="addspecs">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import TopHeader from "./top-header";
import { getFoodlist, getFoodType,updateFood,deleteFood } from "@/api/api";
import { BASE_URL, baseImgPath } from "@/config/env";
import axios from "axios";
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {
    "top-header": TopHeader,
  },
  data() {
    //这里存放数据
    return {
      selectTable: {},
      foodSearch:"",
      specsForm: {
	  specs_name: '',
	  packing_fee: 0,
	  price: 20,
	            },
      addSpecs:false,
      foodListData: [],
      foodListData1: [],
      BASE_URL: BASE_URL,
      baseImgPath: baseImgPath,
      imageUrl: "",
      dialogVisible: false,
      rules: {
          name:[{required:true,message:"请输入食品名称",trigger:"blur"}],
          description:[{required:true,message:"请输入食品描述",trigger:"blur"}],
          
      },
      specsRules:{
         specs_name:[{required:true,message:"请输入规格",trigger:"blur"}]
      },
      form: {},
      value:"",
      selectIndex:null,
      foodtype: [
          {
          value:1,
          label:"热销"
      },
      {
          value:2,
          label:"优惠"
      },{
          value:3,
          label:"水果"
      },
      {
          value:4,
          label:"生鲜"
      },
      ],
      
    };
  },
  //监听属性 类似于data概念
  computed: {
      specs:function(){
        let specs = [];
        if(this.form.specfoods){
        this.form.specfoods.map(item=>{
            specs.push({
                specs_name:item.specs_name,
                packing_fee:item.packing_fee,
                price:item.price
            })
        })
      }
    return specs;
    },
  },
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
      handleDelete:async function(scope){
         const result = await deleteFood(scope.row.item_id);
          if (res.status == 1) {
                        this.$message({
                            type: 'success',
                            message: '删除食品成功'
                        });
                        this.tableData.splice(index, 1);
                    }else{
                         this.$message({
                            type: 'error',
                            message: '删除食品失败'
                        });
                    }
     },
     //点击确定提交修改
     handleSubmit:function(form){
         this.$refs[form].validate(async (valid)=>{
             if(valid){
                 this.$message("准备提交表单");
                 //向后台提交数据
                 let {item_id,name,description ,image_path,restaurant_id,category_id,specfoods} = this.form;
                let result = await updateFood({
                    item_id,
                    name,
                    description,
                    image_path,
                    restaurant_id,
                    category_id,
                    specfoods,
                });
               
                if(result.status === 1){
                    this.dialogVisible = false;
                    this.$message({
                        type:"success",
                        message:"更新成功"
                    });
                }
             }else{
                 this.$message({
                     type:"error",
                     message:"表单有误，请检查"
                 })
             }
         })
     },
    addspecs(){
				this.specs.push({...this.specsForm});
				this.addSpecs = false;
            },
     subspecs(scope){
                let index = scope.$index;
                this.specs.splice(index,1);
                this.form.specfoods = this.specs;
    },
    handleAvatarSuccess(res){
        if (res.status == 1) {
        this.selectTable.image_path = res.image_path;
      } else {
        this.$message.error("上传图片失败！");
      }
     },
     beforeAvatarUpload(file){
         const isLt2M = file.size/1024/1024<2;
         if(!isLt2M){
             this.$message.error("上传图片大小不能超过2M")
         }
         return isLt2M
     },
    handleSearch:function(){
        this.foodListData = this.foodListData1;
        console.log(this.foodSearch);
        let result = [];
        if(this.foodSearch){
            this.foodListData.map(item=>{
                if((item.name).includes(this.foodSearch)){
                    result.push(item)
                }else{
                    console.log(false);
                }
            })
            this.foodListData = result;
            
        }else{
            return
        }
        
    },
    
    //编辑 显示弹出窗口
    handleEdit: async function (scope) {
      this.dialogVisible = true;
      this.form = scope.row;
      //console.log(this.form);
      this.selectTable = scope.row;
      this.imageUrl = baseImgPath + scope.row.image_path;
    },
    
   
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  async created() {
    let res = await getFoodlist();
    // console.log(res);
    this.foodListData = res;
    this.foodListData1 = res;

  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang="less" scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar:hover{
  border-color: #409eff;

}
</style>